<?php

/**
 * 会员管理
 *
 * @package		Hooloo framework
 * @author 		Bill
 * @copyright 	Hooloo Co.,Ltd
 * @version		1.0
 * @release		2017.05.08
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class Ratio extends Controller {
	public function __construct() {
		parent::__construct();
	}
	
	/**
     * 列表
     */
	public function index($aid = 0, $demo_account = 0, $username = 0, $p = 1) {
		//检查所有持仓用户保证金率
		$start = strtotime(date("Y-m-d 00:00:00", strtotime("-10 day")));
		$sql = "select uid from stock_bull where bull_time > $start and can_sell = 1 GROUP BY uid";
		$stock_bull = $this->db->query($sql)->result_array();
		if ($stock_bull) {
			$uid = array_column($stock_bull, "uid");
			$uid = implode(",", $uid);
			
			//指定代理商
			if ($aid == 0) {
				$where = " where aid > 0";
			} else {
				$where = " where aid = $aid";
			}
			
			//持仓用户
			$where .= " and id in (" . $uid . ")";
			
			//帐号类型
			if ($demo_account == 0) {
				$where .= " and demo_account = 0";
			} elseif ($demo_account == 1) {
				$where .= " and demo_account = 1";
			} else {
				$demo_account = 2;
			}
			
			//存在搜索
			if ($username) {
				$where .= " and (username like '%$username%' or realname like '%$username%')";
			} else {
				$username = 0;
			}
			
			//数据分页
			$size = 15;//每页数量
			if (0 >= $p) {
				$p = 1;
			}
			$start = ($p - 1) * $size;
			
			//分页查询
			$sql = "select * from user " . $where;
			$list = $this->db->query($sql)->result_array();
			
			//查询用户信息
			$uid = array_column($list, "id");
			$uid = implode(",", $uid);
			$user = get_user($uid, 1);
			
			//格式化数据
			foreach ($list as $key => $val) {
				$list[$key]["ratio"] = $user[$val["id"]]["ratio"];//保证金率
				$list[$key]["gain"] = $user[$val["id"]]["total_gain"];//浮动盈亏
				$list[$key]["finance"] = $user[$val["id"]]["finance"];//资金余额
				$list[$key]["amount"] = $user[$val["id"]]["amount"];//可用额度
			}
			
			//重新排序
			if ($list) {
				foreach ($list as $v) {
					$ratio[] = $v['ratio'];
				}
				array_multisort($ratio, $list);
			}
			
			//查询总数
			$total = count($list);
			
			//分页数据
			$list = array_slice($list, $start, $size);
			
			//分页展示
			$url = "/" . $this->_controller . '/' . $this->_action . '/' . $aid . "/". $demo_account . "/" . $username . "/";
			$page = page_format($total, $size, $p, $url);
		} else {
			$list = array();
			$page = "";
			$total = 0;
		}
		
		//查询所有代理商
		$sql = "select * from agent";
		$agent = $this->db->query($sql)->result_array();
		
		//分配展示
		$this->assign("list", $list);
		$this->assign("agent",$agent);
		$this->assign("page", $page);
		$this->assign("total", $total);
		
		$this->assign("aid", $aid);
		$this->assign("demo_account", $demo_account);
		$this->assign("username", $username);
		$this->display();
	}
}
